(function (window, $, undefined) {
  'use strict';

  var dictData = {
    cityId: {

    },
    contractCompany: {

    },
    gender: {
      '0': '未知',
      '1': '男',
      '2': '女',
      '9': '未说明'
    },
    commercialType: {

    },
    driverLicenseType: {

    },
    education: {

    },
    nation: {

    },
    state: {
      '1': '未锁定',
      '2': '已锁定'
    },
    orderType: {
      '1': '立即接机',
      '2': '立即接站',
      '3': '预约接机',
      '4': '预约接站',
      '5': '预约送机',
      '6': '预约送站',
      '7': '预约用车',
      '8': '立即用车'
    },
    // 手机运营商
    netType: {
      '1': '中国联通',
      '2': '中国移动',
      '3': '中国电信',
      '4': '其他'
    },
    // 婚姻状态
    maritalStatus: {

    },
    loginState: {

    }
  };

  var driverData = {};

  main(function () {

    var $tableDriver = $('#table-driver');
    util.jqGrid($tableDriver, {
      url: ajaxURL.ORGANIZATION + '/driver/getDriverList',
      // datatype: 'json',
      autowidth: true,
      height: $(window).height() - 350,
      multiselect: true,
      multiboxonly: true,
      // shrinkToFit: false,
      colModel: [
        { label: '编号', key: true, name: 'kid', width: 60 },
        {
          label: '城市', name: 'cityId', width: 60, formatter: function (v, o, r) {
            return dictData.cityId[v] || '';
          }
        },
        { label: '所属人力公司', name: 'contractCompany', width: 220 },
        {
          label: '姓名', name: 'name', width: 100, formatter: function (v, o, r) {
            return '<a href="javascript:;" class="view" data-id="' + r.kid + '">' + v + '</a>';
          }
        },
        {
          label: '性别', name: 'gender', width: 40, formatter: function (v, o, r) {
            return dictData.gender[v] || '';
          }
        },
        {
          label: '年龄', name: 'age', width: 40, formatter: function (v, o, r) {
            // 根据身份证号码推算年龄
            var id = r.idCardNumber + '';
            var age = '';
            var birthYear = (id + '').substr(6, 4);
            var curYear = new Date().getFullYear();
            if (birthYear) {
              age = curYear - birthYear;
            }
            return age;
          }
        },
        { label: '身份证', name: 'idCardNumber', hidden: true },
        { label: '身份证', name: 'idCardNumberX', width: 180, formatter: function (v, o, r) {
          var idCardNumber = r.idCardNumber;
          var ret = idCardNumber.substr(0, 5) + '********' + idCardNumber.substr(13)
          return ret;
        } },
        { label: '司机等级', name: 'level', width: 80 },
        { label: '司机评分', name: 'point', width: 80 },
        { label: '绑定车型', name: 'autoId', width: 80 },
        { label: '绑定车牌号', name: 'autoNo', width: 110 },
        {
          label: '录入时间', name: 'createTime', width: 100, formatter: function (v, o, r) {
            return util.getDate(v);
          }
        },
        {
          label: '登录状态', name: 'loginState', width: 80, formatter: function (v) {
            return dictData.loginState[v] || '';
          }
        },
        { label: '排班状态', name: 'workState', width: 70 },
        { label: '当前代付欠款', name: 'loan', width: 100 },
        { label: '锁定状态', name: 'state', width: 80, formatter: function (v, o, r) {
          return dictData.state[v] || '';
        } }
      ],
      loadComplete: function (res) {
        driverData = {};
        if (res && res.data) {
          $.each(res.data, function (_, item) {
            driverData[item.kid] = item;
          });
        }
      },
      pager: '#pager-driver'
    });

    laydate.render({
      elem: '#createDate' //指定元素
    });

    var $searchCondition = $('.search-condition');

    // 手机运营商下拉添加
    util.selectHtml('select[name="netType"]', dictData.netType, '', '', '请选择');
    util.selectHtml('select[name="maritalStatus"]', dictData.maritalStatus, '', '', '请选择');
    util.selectHtml('select[name="state"]', dictData.state, '', '', '请选择');

    var dictList = [
      'nation',
      'gender',
      'education',
      'driverLicenseType',
      'commercialType',
      'maritalStatus'
    ];
    var dictName = [
      'nation',
      'gender',
      'education',
      'driverType',
      'commercialType',
      'maritalStatus'
    ];

    util.promiseAll([
      ajaxURL.ORGANIZATION + '/company/getCompanyList?pageNum=1&pageSize=99999',
      ajaxURL.ORGANIZATION + '/city/getCityList?pageNum=1&pageSize=99999'
    ], [
      function (res) {
        $('#contractCompany-search').sinput({
          data: res.data,
          text: 'serviceName',
          extraData: ['kid'],
          extraDataName: ['companyId']
        });
        $('#contractCompany-edit').sinput({
          data: res.data,
          text: 'serviceName',
          placeholder: '请选择人力服务公司',
          extraData: ['kid'],
          extraDataName: ['companyId'],
          zIndex: 9999999999
        });
      },
      function (res) {
        util.selectHtml($('select[name="cityId"]'), res.data, 'cityId', 'name', '请选择');
        $.each(res.data, function (_, item) {
          dictData.cityId[item.cityId] = item.name;
        });
      }
    ]).then(function () {
      util.getDicts(dictList).then(function (datas) {
        $.each(datas, function (_, data) {
          util.selectHtml('[name="' + dictName[_] + '"]', data, 'value', 'name', '请选择');
          $.each(data, function (x, item) {
            dictData[dictList[_]][item.value] = item.name;
          });
        });

        searchTable();
        $('#btn-search').click(searchTable);
      });
    });

    // 搜索表格
    function searchTable() {
      var data = util.formData('#form-search');
      if (data.createTime) {
        data.createTime = util.getTime(data.createTime)
      } else {
        data.createTime = '';
      }
      util.searchGrid($tableDriver, data);
    }

    var $layerDriver = $('#layer-driver-detail');
    var $formDriver = $('#form-driver-detail');
    var $saveDriver = $('#driver-save');

    // 图片的处理
    var $driverHeadImg = $('#driver-headImg');
    var $driverHeadImgUpload = $('#driver-headimg-upload');
    var $driverHeadImgThumb = $('#driver-headImg-thumb');

    // 头像上传操作
    util.upload($driverHeadImgUpload, function (res) {
      util.tip.success('图片上传成功');
      $driverHeadImg.val(res.data);
      $driverHeadImgUpload.siblings('img').attr('src', util.pic(res.data));
    });

    $('#driver-headImg-thumb').click(function () {
      var id = $driverHeadImg.val();
      var $img = $(this).clone();
      if (id) {
        $('#layer-view-img').find('img').attr('src', util.pic(id));
        util.layerOpen({
          title: '查看司机头像图片',
          content: $('#layer-view-pic')
        });
      }
    });

    // 驾照图片上传操作
    util.upload('#licensePhotoImg-upload', function (res) {
      util.tip.success('图片上传成功');
      $('#licensePhotoImg-preview').attr('src', util.pic(res.data));
      $('#licensePhotoImg').val(res.data);
    });

    $('#licensePhotoImg-preview').click(function () {
      var id = $('#licensePhotoImg').val();
      if (id) {
        $('#layer-view-img').find('img').attr('src', util.pic(id));
        util.layerOpen({
          title: '查看驾驶证图片',
          content: $('#layer-view-pic')
        });
      }
    });

    $('#licensePhotoImg-del').click(function () {
      var id = $('#licensePhotoImg').val();
      if (id) {
        layer.confirm('驾驶证图片为必填值，确认进行清除操作？', function (index) {
          $('#licensePhotoImg-preview').attr('src', '/images/1x1.png');
          $('#licensePhotoImg').val('');
          layer.close(index);
        });
      }
    });

    // 保险单片上传操作
    util.upload('#insuranceImg-upload', function (res) {
      util.tip.success('图片上传成功');
      $('#insuranceImg-preview').attr('src', util.pic(res.data));
      $('#insuranceImg').val(res.data);
    });

    $('#insuranceImg-preview').click(function () {
      var id = $('#insuranceImg').val();
      if (id) {
        $('#layer-view-img').find('img').attr('src', util.pic(id));
        util.layerOpen({
          title: '查看图片',
          content: $('#layer-view-pic')
        });
      }
    });

    $('#insuranceImg-del').click(function () {
      var id = $('#insuranceImg').val();
      if (id) {
        layer.confirm('该图片为必填值，确认进行清除操作？', function (index) {
          $('#insuranceImg-preview').attr('src', '/images/1x1.png');
          $('#insuranceImg').val('');
          layer.close(index);
        });
      }
    });

    var $validateDriver = $formDriver.validate({
      rules: {
        headImg: { required: true },
        cityId:{required:true},
        phone: { required: true ,phone:true},
        gender: { required: true },
        name: { required: true, stringCheck: true },

        cityId: { required: true },
        idCardNumber: { required: true, isIdCard2: true },
        nationality: { required: true },
        nation: { required: true },
        address: { required: true },
        maritalStatus: { required: true },
        languageLevel: { required: true },
        education: { required: true },
        census: { required: true },
        // address: { required: true },

        licenseId: { required: true },
        driverType: { required: true },
        getDriverLicenseDate: { required: true },
        driverLicenseActiveDate: { required: true },
        certificateNo: { required: true },
        networkCarIssueOrganization: { required: true },
        networkCarIssueDate: { required: true },
        getNetworkCarProofDate: { required: true },
        networkCarProofDate: { required: true },
        registerDate: { required: true },
        contractCompany: { required: true },
        contractDate: { required: true },

        commercialType: { required: true },
        texiDriver: { required: true },
        fullTimeDriver: { required: true },
        emergencyContact: { required: true ,stringCheck:true },
        emergencyContactPhone: { required: true,phone:true },
        emergencyContactAddress: { required: true },

        netType: { required: true },
        insuranceImg: { required: true }
      },
      messages: {
        headImg: { required: '请上传头像' },
        // cityId:{required:'请选择城市'},
        // phone: { required: '联系电话不能为空' },
        // gender: {
        //   required: '请选择性别'
        // },
        // name:{required:'姓名不能为空'},
        // idCardNumber:{required:'身份证号不能为空'},
        // phone:{required:'手机号不能为空'},
        // nationality:{required:'请输入国籍'},
        // nation:{required:'请选择民族'},
        // address:{required:'请输入您的详细地址'},
        // maritalStatus:{required:'请选择婚姻状态'},
        // languageLevel:{required:'请输入您的外语能力'},
        // education:{required:'请选择您的学历'},
        // census:{required:'请输入户口登记机关'},
        // address:{required:'请输入户口地址'},
        // licenseId:{required:'请输入驾驶证件号'},
        // driverType:{required:'请选择驾驶证类型'},
        // getDriverLicenseDate:{required:'请选择发证日期'},
        // driverLicenseActiveDate:{required:'请输入驾照有效期'},
        // certificateNo:{required:'请输入驾驶证资格号'},
        // networkCarIssueOrganization:{required:'请输入发证机构'},
        // networkCarIssueDate:{required:'请选择发证日期'},
        // getNetworkCarProofDate:{required:'请选择初次领证日期'},
        // networkCarProofDate:{required:'请选择有效期'},
        // registerDate:{required:'请选择报备日期'},
        // contractCompany:{required:'请选择所属人力公司'},
        // contractDate:{required:'请选择合同日期'},
        // commercialType:{required:'请选择服务类型'},
      },
      errorPlacement: function (error, element) { //错误信息位置设置方法
        error.appendTo(element.parents('.form-container')); //这里的element是录入数据的对象
      }
    });

    // 新增与修改时的时间选择
    laydate.render({
      elem: '#getDriverLicenseDate'
    });
    laydate.render({
      elem: '#networkCarIssueDate'
    });
    laydate.render({
      elem: '#getNetworkCarProofDate'
    });
    laydate.render({
      elem: '#registerDate'
    });

    laydate.render({
      range: '至',
      elem: '#driverLicenseActiveDate',
      done: function (value, date, endDate) {
        var temp = value.split('至');
        $('#driverLicenseActiveDate').next().val($.trim(temp[0])).next().val($.trim(temp[1]));
      }
    });

    laydate.render({
      range: '至',
      elem: '#networkCarProofDate',
      done: function (value, date, endDate) {
        var temp = value.split('至');
        $('#networkCarProofDate').next().val($.trim(temp[0])).next().val($.trim(temp[1]));
      }
    });

    laydate.render({
      range: '至',
      elem: '#contractDate',
      done: function (value, date, endDate) {
        var temp = value.split('至');
        $('#contractDate').next().val($.trim(temp[0])).next().val($.trim(temp[1]));
      }
    });

    // 新增操作
    $('#btn-add').click(function () {
      $layerDriver.find(':input').removeAttr('disabled');
      util.resetForm($formDriver);
      $saveDriver.parent().removeClass('hide');

      // 防止无法清除的 kid 的问题
      $formDriver.find('[name="kid"]').val('');

      util.layerOpen({
        // title: '平台司机管理 - 新增',
        title: false,
        content: $layerDriver,
        area: ['1000px', ''],
        btn: ['确认新增', '取消'],
        yes: function() {
          driverSave()
        },
        cancel: function (index) {
          layer.confirm('确定退出当前页面？', {
            btn: ['确定', '再想一想'],
            yes: function (idx) {
              layer.close(index);
              layer.close(idx);
            }
          });
          return false;
        }
      });
    });

    // $('#driver-save').click(function () {
    function driverSave() {
      var data = util.formData($formDriver);

      if (!data.headImg) {
        return util.tip.warn('请先上传司机头像图片');
      }

      if (!data.licensePhotoImg) {
        return util.tip.warn('请先上传驾驶证图片');
      }

      if (!data.insuranceImg) {
        return util.tip.warn('请先上传车辆保险单图片');
      }

      // 表格数据验证
      if ($validateDriver.form()) {


        util.toTimeStamp(data, [
          'getDriverLicenseDate',
          'driverLicenseOn',
          'driverLicenseOff',
          'networkCarIssueDate',
          'getNetworkCarProofDate',
          'networkCarProofOn',
          'networkCarProofOff',
          'registerDate',
          'contractOn',
          'contractOff'
        ]);

        data.addressCityId = data.cityId;
        data.emergencyContactAddressCityId = data.cityId;
        data.inDriverBlackList = 0;

        // 根据身份证生成生日的时间戳
        var idCardNumber = data.idCardNumber;
        var strBirth = String(idCardNumber).substr(6,8);
        strBirth = strBirth.replace(/^(\d{4})(\d{2})/, function (_, a, b) {
          return a + '-' + b + '-';
        });

        data.brithday = util.getTime(strBirth); // 1511248354000;

        // data.licensePhotoImg = 'f8640e2e7e1a4b2687cfb61e702d25c3';
        // data.headImg = 'f8640e2e7e1a4b2687cfb61e702d25c3';
        data.state = 1;

        data.contractAddressCityId = data.cityId;
        data.contractAddress = data.address;

        // data.mac = data.mac || '00:00:00:00:00:00';
        // data.imei = data.imei || '-1';
        // data.imsi = data.imsi || '-1';

        // data.kid 来决定是什么操作，有为修改，无为新增
        var url = ajaxURL.ORGANIZATION + (data.kid ? '/driver/updateDriver' : '/driver/addDriver');
        util.ajax(url, JSON.stringify(data), 'POST', util.resCallback(function (res) {
          layer.closeAll();
          util.tip.success('操作成功');
          $tableDriver.trigger('reloadGrid');
        }));

      } else {
        util.tip.warn('请将数据填写完整');
      }
    }
    // });

    // 查看司机
    $tableDriver.on('click', '.view', function () {
      var $this = $(this);
      var id = $this.data('id');

      var data = driverData[id];

      $layerDriver.find(':input').attr('disabled', 'disabled');
      util.resetForm($formDriver);
      $saveDriver.parent().addClass('hide');

      // 时间处理
      data.driverLicenseActiveDate = util.getDate(data.driverLicenseOn) + ' 至 ' + util.getDate(data.driverLicenseOff);
      data.getDriverLicenseDate = util.getDate(data.getDriverLicenseDate);
      data.getNetworkCarProofDate = util.getDate(data.getNetworkCarProofDate);
      data.networkCarProofDate = util.getDate(data.networkCarProofOn) + ' 至 ' + util.getDate(data.networkCarProofOff);
      data.registerDate = util.getDate(data.registerDate);
      data.networkCarIssueDate = util.getDate(data.networkCarIssueDate);
      data.contractDate = util.getDate(data.contractOn) + ' 至 ' + util.getDate(data.contractOff);

      util.fillForm($formDriver, data);

      // 图片的处理
      $driverHeadImgThumb.attr('src', data.headImg ? util.pic(data.headImg) : '/images/member.png');
      $('#licensePhotoImg-preview').attr('src', data.licensePhotoImg ? util.pic(data.licensePhotoImg) : '/images/1x1.png');
      $('#insuranceImg-preview').attr('src', data.insuranceImg ? util.pic(data.insuranceImg) : '/images/1x1.png');

      util.layerOpen({
        // title: '平台司机管理 - 详情',
        title: false,
        content: $layerDriver,
        area: ['1000px', '']
      });

    });

    // 修改司机
    $('#btn-edit').click(util.oneCheck($tableDriver, function (id) {
      var data = driverData[id];

      $layerDriver.find(':input').removeAttr('disabled');
      util.resetForm($formDriver);
      $saveDriver.parent().removeClass('hide');

      // 时间处理
      data.driverLicenseActiveDate = util.getDate(data.driverLicenseOn) + ' 至 ' + util.getDate(data.driverLicenseOff);
      data.getDriverLicenseDate = util.getDate(data.getDriverLicenseDate);
      data.getNetworkCarProofDate = util.getDate(data.getNetworkCarProofDate);
      data.networkCarProofDate = util.getDate(data.networkCarProofOn) + ' 至 ' + util.getDate(data.networkCarProofOff);
      data.registerDate = util.getDate(data.registerDate);
      data.networkCarIssueDate = util.getDate(data.networkCarIssueDate);
      data.contractDate = util.getDate(data.contractOn) + ' 至 ' + util.getDate(data.contractOff);

      util.fillForm($formDriver, data);

      // 图片的处理
      $driverHeadImgThumb.attr('src', data.headImg ? util.pic(data.headImg) : '/images/member.png');
      $('#licensePhotoImg-preview').attr('src', data.licensePhotoImg ? util.pic(data.licensePhotoImg) : '/images/1x1.png');
      $('#insuranceImg-preview').attr('src', data.insuranceImg ? util.pic(data.insuranceImg) : '/images/1x1.png');

      util.layerOpen({
        // title: '平台司机管理 - 修改',
        title: false,
        content: $layerDriver,
        area: ['1000px', ''],
        btn: ['确认修改', '取消'],
        yes: function () {
          driverSave()
        },
        cancel: function (index) {
          layer.confirm('确定退出当前页面？', {
            btn: ['确定', '再想一想'],
            yes: function (idx) {
              layer.close(index);
              layer.close(idx);
              loadAutoModel();
            }
          });
          return false;
        }
      });
    }));

    // 删除司机
    $('#btn-del').click(util.oneCheck($tableDriver, function (id) {
      layer.confirm('确定删除该司机？', {
        btn: ['确定', '再想一想']
      }, function () {
        util.ajax(ajaxURL.ORGANIZATION + '/driver/removeDriver?kid=' + id, '', 'POST', util.resCallback(function (res) {
          util.tip.success('删除成功');
          $tableDriver.trigger('reloadGrid');
        }));
      });
    }));

    // 重置密码
    $('#btn-resetpwd').click(util.oneCheck($tableDriver, function (id) {
      layer.confirm('确定重置密码？', {
        btn: ['确定', '再想一想']
      }, function () {
        util.tip.warn('重置密码操作...');
      });
    }));

    //为null时处理
    function estimateNull(option) {
      if (option === null) {
        return ' ';
      } else {
        return option
      }
    }

    // 查看订单
    $('#btn-vieworder').click(util.oneCheck($tableDriver, function (id) {
      var urlFin = ajaxURL.ORDER + '/order/list?status=1&driver_id=' + id;
      var urlUnfin = ajaxURL.ORDER + '/order/list?status=2&driver_id=' + id;

      //已完成订单查看
      util.get(urlFin, util.resCallback(function (res) {
        var finishedOrderCount = res.data.length;
        $("#finished").text(finishedOrderCount);
        if (finishedOrderCount === 0) {
          $('#order-finished').html('<h3>已完成订单为' + finishedOrderCount + '！<h3>')
        } else {
          var html = "";
          var data = res.data;
          for (var i = 0; i < data.length; i++) {
            // if (data[i].passengerName) { }
            html +='<div class="h3">已完成</div><div class="order-list"><div class="order-info"><p>订单类型：<span>'+dictData.orderType[data[i].orderType]+'</span></p><p>订单编号：<span>'+data[i].orderNo+'</span></p><p>出发地点：<span>'+data[i].actualOrig+'</span></p><p>到达地点：<span>'+data[i].actualDest+'</span></p></div><div class="order-overview"><div class="order-price"><p>预估价：<u data-vprice>'+util.price(data[i].planPrice)+'</u></p><p class="time">下单时间<span>'+util.dateFormat(data[i].createTime)+'</span></p></div><div class="order-person"><p>用车人：'+estimateNull(data[i].passengerName)+'</p><p>用车电话：'+data[i].passengerPhone+'</p><p class="spec">用车时间：'+util.dateFormat(data[i].depTime)+'</p></div></div></div>'
          }
          $("#order-finished").html(html)

        }
      }));

      //未完成订单查看
      util.get(urlUnfin,function(res){
        var unfinishedOrderCount = res.data.length;
        $("#unfinished").text(unfinishedOrderCount);
        if (unfinishedOrderCount === 0) {
          $('#order-unfinished').html('<h3>未完成订单为' + unfinishedOrderCount + '！<h3>')
        } else {
          var html = "";
          var data = res.data;
          data.planPrice = util.price(data.planPrice);
          for (var i = 0; i < data.length; i++) {
            html +='<div class="h3">已完成</div><div class="order-list"><div class="order-info"><p>订单类型：<span>'+dictData.orderType[data[i].orderType]+'</span></p><p>订单编号：<span>'+data[i].orderNo+'</span></p><p>出发地点：<span>'+data[i].actualOrig+'</span></p><p>到达地点：<span>'+data[i].actualDest+'</span></p></div><div class="order-overview"><div class="order-price"><p>预估价：<u data-vprice>￥'+data[i].planPrice+'</u></p><p class="time">下单时间<span>'+util.dateFormat(data[i].createTime)+'</span></p></div><div class="order-person"><p>用车人：'+estimateNull(data[i].passengerName)+'</p><p>用车电话：'+data[i].passengerPhone+'</p><p class="spec">用车时间：'+util.dateFormat(data[i].depTime)+'</p></div></div></div>'
          }
          $("#order-unfinished").html(html)

        }
      });


      util.layerOpen3({
        title: '平台司机管理 - 订单查看',
        content: $('#layer-driver-order')
      });
    }));

    // 订单切换
    $('.tab-navitem').click(function () {
      var $this = $(this);
      var index = $this.index();
      if ($this.hasClass('on')) {
        return;
      }
      $this.addClass('on').siblings().removeClass('on');
      $('.tab-content').addClass('hide').eq(index).removeClass('hide');
    });

    // 锁定
    $('#btn-lock').click(util.oneCheck($tableDriver, function (id) {
      var data = driverData[id];
      if (+data.state === 2) {
        return util.tip.warn('该司机已经处于锁定状态！');
      }

      layer.confirm('确定锁定该司机？锁定后该司机的相关操作将会受到影响，请谨慎操作', {
        btn: ['确定', '再想一想']
      }, function () {
        data.state = 2;
        updateDriver(data);
      });

    }));

    // 解锁操作
    $('#btn-unlock').click(util.oneCheck($tableDriver, function (id) {
      var data = driverData[id];
      if (+data.state === 1) {
        return util.tip.warn('该司机未处于锁定状态！');
      }

      layer.confirm('确定解锁该司机？', {
        btn: ['确定', '再想一想']
      }, function () {
        data.state = 1;
        updateDriver(data);
      });

    }));

    // 更新司机
    function updateDriver(data) {
      util.post(ajaxURL.ORGANIZATION + '/driver/updateDriver', data, function (res) {
        layer.closeAll();
        util.tip.success('操作成功');
        $tableDriver.trigger('reloadGrid');
      });
    }


  });


})(window, jQuery);
